﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace HY.Framework.Castle
{
    public interface IReIsolatedCache : ICache
    {
        void IsolatedAdd(string key, object value);
        object IsolatedGet(string key);
        void IsolatedRemove(string key);
        void IsolatedClear();
    }

    internal class ReIsolatedCache : SysCache, IReIsolatedCache
    {
        public void IsolatedAdd(string key, object value)
        {
            key = CombineKey(key);
            if (key != null)
                this.Add(key, value);
        }

        public object IsolatedGet(string key)
        {
            key = CombineKey(key);
            if (key != null)
                return this.Get(key);
            else
                return null;
        }

        public void IsolatedRemove(string key)
        {
            key = CombineKey(key);
            if (key != null)
                this.Remove(key);
        }

        public void IsolatedClear()
        {
            IList<string> keys = new List<string>();

            foreach (DictionaryEntry entry in this)
            {
                string key = entry.Key as string;
                if (key != null && key.StartsWith(ServerApplication.PrimeTag + "_"))
                    keys.Add(key);
            }

            foreach (string key in keys)
                this.Remove(key);
        }

        private string CombineKey(string key)
        {
            if (!String.IsNullOrEmpty(ServerApplication.PrimeTag) && !String.IsNullOrEmpty(key))
            {
                return ServerApplication.PrimeTag + "_" + key;
            }

            return null;
        }
    }
}
